package com.dbappsecurity.network.download;

import android.os.Environment;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import java.io.File;
import okio.BufferedSink;
import okio.BufferedSource;
import okio.Okio;
import okio.Sink;
import retrofit2.Retrofit;

import static android.os.Environment.DIRECTORY_PICTURES;

public class Download {
  String mUrl;
  File mFile;
  Retrofit mRetrofit;

  public Download(String url, Retrofit retrofit) {
    mUrl = url;
    mRetrofit = retrofit;
    mFile = new File(Environment.getExternalStoragePublicDirectory(DIRECTORY_PICTURES),
        System.currentTimeMillis() + ".jpg");
  }

  public Disposable start() {
    return mRetrofit.create(DownloadService.class)
        .get(mUrl)
        .subscribeOn(Schedulers.io())
        .subscribe(responseBody -> {
          BufferedSource bufferedSource = responseBody.source();
          try (Sink fileSink = Okio.sink(mFile);
               BufferedSink bufferedSink = Okio.buffer(fileSink)) {
            bufferedSink.writeAll(bufferedSource);
          }
        });
  }
}
